package com.example.pacs.dicom.server.cfind;

import com.example.pacs.bean.request.QueryParamsRequest;
import com.example.pacs.dao.DicomServerMapper;
import org.dcm4che3.data.Attributes;
import org.dcm4che3.data.Tag;
import org.dcm4che3.data.UID;
import org.dcm4che3.data.VR;
import org.dcm4che3.net.Association;
import org.dcm4che3.net.pdu.PresentationContext;
import org.dcm4che3.net.service.BasicCFindSCP;
import org.dcm4che3.net.service.QueryTask;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * worklist SUP实现
 */
@Component
public class MWLCFindSUP extends BasicCFindSCP {

    @Resource
    private DicomServerMapper dicomServerMapper;

    /**
     * 填充这个SUP提供的功能(SOP CLASS UID)
     */
    public MWLCFindSUP() {
        super(UID.ModalityWorklistInformationModelFIND, UID.StudyRootQueryRetrieveInformationModelFIND);
    }

    /**
     * 重新计算匹配规则
     *
     * @param as 连接信息
     * @param pc 描述上下文
     * @param rq 请求
     * @param keys 查询参数
     * @return 执行数据填充的任务执行类
     */
    @Override
    protected QueryTask calculateMatches(Association as, PresentationContext pc, Attributes rq, Attributes keys) {
        // 获取worklist查询参数
        QueryParamsRequest params = QueryParamsRequest.builder()
                .patientId(keys.getString(Tag.PatientID))
                .patientName(keys.getString(Tag.PatientName))
                .modalityType(keys.getString(Tag.Modality))
                .startStudyDateAndTime(keys.getDate(Tag.ScheduledStudyStartDateAndTime))
                .endStudyDateAndTime(keys.getDate(Tag.ScheduledStudyStopDateAndTime))
                .build();
        return new MWLQueryTask(as, pc, rq, createReturnKeys(keys), dicomServerMapper, params);
    }

    /**
     * 构建返回attributes基础编码属性
     *
     * @param keys 返回attributes
     * @return 返回attributes
     */
    private Attributes createReturnKeys(Attributes keys) {
        Attributes returnKeys = new Attributes(keys.size() + 3);
        returnKeys.addAll(keys);
        returnKeys.setNull(Tag.SpecificCharacterSet, VR.CS);
        return returnKeys;
    }
}
